import React, {PureComponent} from 'react';
import { Form, Input, Modal,Row,Col,Card,Tree,Button } from 'antd';
import moment from 'moment';
import TableList from '@/components/TableList';
import styles from '@/pages/search.less';

const FormItem = Form.Item;
const {TextArea} = Input;
const {DirectoryTree, TreeNode} = Tree;
const formLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 18},
};
// 申请详情页面，包含审核
@Form.create()
class BindPerson extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      selectedRows: [],
      orgId: '',//树节点ID
      roleId: '',
      selectedRowKeys: [], // 勾选几项，下次默认进来勾选
      isHandTable: false,
    };
  }


  renderForm () {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
        <Col md={10} sm={24}>
          <FormItem label="姓名" {...formLayout}>
            {getFieldDecorator('userName')(<Input placeholder="请输入"/>)}
          </FormItem>
        </Col>
        <Col md={10} sm={24}>
          <FormItem label="登录名" {...formLayout}>
            {getFieldDecorator('userCode')(<Input placeholder="请输入"/>)}
          </FormItem>
        </Col>
        <Col md={4} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
        </Col>
        </Row>
      </Form>
    );
  };

  handleSearch = e => {
    e.preventDefault();
    const {orgList, form} = this.props;
    const {orgId} = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      })
      fieldsValue.orgId = orgId;
      //点击查询
      orgList(fieldsValue);
      this.resetSelectedRows();
    });
  };

  okHandle = () => {
    const { form, userInfo, orgDataList } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      const {selectedRows, roleId, isHandTable} = this.state;
      let userCodeList = '';
      if(isHandTable) {
        userCodeList = selectedRows.map((v)=>{
          return v.userCode
        }).join(',');
      }else{
        const dataList = orgDataList&&orgDataList.dataList;
        let newArr = [];
        dataList&&dataList.length&&dataList.map((v,i) => {
          if(v.checkedFlag){
            newArr.push(v)
          }
        })
        userCodeList = newArr&&newArr.length?newArr.map((v)=>{
          return v.userCode
        }).join(','):'';
      }

     this.props.bindUserRole({roleId:userInfo.id,userCodeList});
     this.setState({
        selectedRows: [],
        roleId: '',
     })
    });
  };

  handleUserList = (pagination) => {
    const { treeDataList } = this.props;
    const { userInfo } = this.props;
    const { orgId } = this.state;
    const roleId = userInfo.id;
    const userLevel = userInfo.levelScore;
    this.props.orgList({orgId: orgId?orgId:treeDataList[0].id,roleId,userLevel},pagination.pageSize,pagination.current-1);
  }

  componentDidMount() {
    const { treeDataList,orgDataList,userInfo } = this.props;
    const orgId = treeDataList[0].id;
    const roleId = userInfo.id;
    const userLevel = userInfo.levelScore;
    this.props.orgList({orgId,roleId,userLevel});
  }

  onSelect = (info) => {
    const { userInfo } = this.props;
    const orgId = info[0];
    const roleId = userInfo.id;
    const userLevel = userInfo.levelScore;
    if(!orgId) {
      return
    }

    this.props.orgList({orgId,roleId,userLevel});
    this.setState({
      orgId,
      roleId:orgId,
    })
  }

  handleSelectRowsNew = (selectedRows) => {
    this.setState({
      selectedRows: selectedRows,
      isHandTable: true,
    });
  };

  render() {
    const { bindUserVisible, handleBindUserVisible, treeDataList,orgDataList } = this.props;
    const { selectedRows, selectedRowKeys } = this.state;
    const columns = [
    {
      title: '姓名',
      width:'45%',
      dataIndex: 'userName',

    },
    {
      title: '登录名',
      width:'45%',
      dataIndex: 'userCode',
    }
  ];

    //当前页面状态
    const loop = data => data.map((item) => {
      if (item.children) {
        return (
          <TreeNode key={item.id} title={item.orgName} {...item}>
            {loop(item.children||[])}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={item.orgName} {...item}/>;
    });
    return (
      <Modal
        destroyOnClose
        width={900}
        title="人员设置"
        visible={bindUserVisible}
        onOk={this.okHandle}
        onCancel={() => handleBindUserVisible()}
        bodyStyle={{padding:'0'}}
        maskClosable={false}
      >
          <Row gutter={8}>
            <Col lg={7} md={24}>
              <Card bordered={false}>
              <div className={styles.modalTreeScroll}>
                <Tree
                  showLine={true}
                  onSelect={this.onSelect}
                  defaultExpandedKeys={['1']}
                >
                  {loop(treeDataList||[])}

                </Tree>
                </div>
              </Card>
            </Col>
            {
            <Col lg={17} md={24}>
              <Card bordered={false} bodyStyle={{padding: '24px 24px 24px 0'}}>
              {/*{this.renderForm()}          */}
                <TableList
                  className={styles.tdPadding}
                  selectedRows={selectedRows}
                  loading={false}
                  data={orgDataList}
                  columns={columns}
                  onSelectRow={this.handleSelectRowsNew}
                  onChange={this.handleUserList}
                  rowKey={record => record.userId}
                />
              </Card>
            </Col>
          }
          </Row>
    </Modal>
    );
  }
}

export default BindPerson;
